/*
*   @Author: 1296
*   @Date: 2025-03-16
*   @Description: 导入文件
*/

<template>
  <div class="file-upload-container">
    <input type="file" ref="fileInput" @change="handleFileChange" style="display: none" />
    <div class="button-group">
      <button class="select-button" @click="selectFile">{{ $t('SelectFiles') }}</button>
      <button class="upload-button" @click="uploadFile" :disabled="!selectedFile">{{ $t('UploadFiles') }}</button>
    </div>
    <div class="file-info">
      <p v-if="selectedFile" class="file-name">{{ $t('SelectedFile') }}: {{ selectedFile.name }}</p>
      <p v-if="message" class="message">{{ message }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { useI18n } from 'vue-i18n';
import store from "@/store";

const { t } = useI18n();
const fileInput = ref(null);
const selectedFile = ref(null);
const message = ref('');

const selectFile = () => {
  fileInput.value.click();
};

const handleFileChange = (event) => {
  const files = event.target.files;
  if (files.length > 0) {
    selectedFile.value = files[0];
    message.value = ''; // 清除之前的消息
  }
};

const uploadFile = async () => {
  if (selectedFile.value) {
    const fd = new FormData();
    fd.append('file', selectedFile.value);
    try {
      const res = await axios.post(store.getters.getBaseURL + '/excel/upload', fd, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      message.value = res.data;
      // 上传成功后可选操作：清空已选文件
      selectedFile.value = null;
      fileInput.value.value = '';
    } catch (error) {
      message.value = t('FileLoadingError');
    }
  }
};
</script>

<style scoped>
.file-upload-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
  justify-content: center;
}

.file-info {
  text-align: center;
}

.select-button,
.upload-button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.file-name {
  color: #666;
  font-size: 14px;
  margin: 8px 0;
  word-break: break-all;
}

.select-button {
  background-color: #007bff;
  color: white;
}

.select-button:hover {
  background-color: #0056b3;
}

.upload-button {
  background-color: #28a745;
  color: white;
}

.upload-button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.upload-button:not(:disabled):hover {
  background-color: #218838;
}

.message {
  margin-top: 8px;
  padding: 10px;
  border-radius: 4px;
  background-color: #e9ecef;
  color: #ff0000;
  font-size: 14px;
}
</style>